package com.ls.lserp.modules.trade.web;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.trade.entity.CartonInfo;
import com.ls.lserp.modules.trade.entity.Enchase;
import com.ls.lserp.modules.trade.service.EnchaseService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

/**
 * @ClassName: EnchaseController
 * @Description: 装箱单
 * 
 * @author
 * @date 2017年3月24日 下午18:40:00
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/enchase/single")
public class EnchaseController extends BaseController {

	@Autowired
	// 保存 编辑 删除 方法
	private EnchaseService enchaseService;
	@Autowired
	Configuration freemarkerConfiguration;

	@ModelAttribute
	public Enchase get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {

			// 执行查询语句 查询基本信息
			return enchaseService.get(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new Enchase();
		}
	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("enchase:single:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/trade/enchase";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param enchase
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("enchase:single:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Enchase enchase, HttpServletRequest request, HttpServletResponse response, Model model)
			throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "enchase");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 箱单号
		searchParam.append("&packageNo=");
		searchParam.append(enchase.getPackageNo());
		// 客户合同单号
		searchParam.append("&customerContractNo=");
		searchParam.append(enchase.getCustomerContractNo());
		// 款号
		searchParam.append("&styleCustomerNo=");
		searchParam.append(enchase.getStyleCustomerNo());
		// 款式名称
		searchParam.append("&styleNameCn=");
		searchParam.append(enchase.getStyleNameCn());
		// 客户名
		searchParam.append("&ognizationName=");
		searchParam.append(enchase.getOgnizationName());
		// 状态
		searchParam.append("&tabPageStatus=");
		searchParam.append(enchase.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());

		// 查询一览页面数据
		Page<Enchase> page = enchaseService.findList(new Page<Enchase>(request, response), enchase);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("enchases", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("enchase.ftl"),
				map);
		listMap.put("enchase", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 进入编辑页面
	 * 
	 * @param enchase
	 * @param model
	 * @return
	 */
	@RequiresPermissions("enchase:single:edit")
	@RequestMapping(value = "form")
	public String form(Enchase enchase, RedirectAttributes redirectAttributes, Model model, HttpSession session) {
		if (enchase.getId() != null) {
			// 设定款式一览信息
			List<Enchase> resultIndentList = enchaseService.findIndentList(enchase.getIndentId());

			// 尺码一览
			List<Enchase> resultSizeList = enchaseService.findSizeList(enchase.getIndentId());
			enchase.setAllSizeList(resultSizeList);

			// 箱单明细一览取得
			List<Enchase> resultPackageDetailsList = enchaseService.findPackageDetailsList(enchase);
			if (!CollectionsUtils.isEmpty(resultPackageDetailsList)) {
				enchase.setPackageDetailsList(
						enchaseService.setPackageDetailsList(resultPackageDetailsList, resultSizeList));

				enchase.setIndentList(
						enchaseService.findShowIndentList(enchase.getPackageDetailsList(), resultIndentList));

				enchase.setCartonInfoList(enchaseService.findShowCartonInfoList(enchase.getPackageDetailsList()));

				enchase.setColorList(enchaseService.findColorList(resultIndentList));
			}
		} else {
			enchase.setPackageRoughWeight(new BigDecimal("0"));
			enchase.setPackageNetWeight(new BigDecimal("0"));
			enchase.setPackageVolume(new BigDecimal("0"));
		}

		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("enchase", enchase);

		// 返回页面地址
		return "modules/trade/enchaseCreate";
	}

	/**
	 * 纸箱选择页面
	 * 
	 * @param cartonInfo
	 * @param model
	 * @return
	 */
	@RequiresPermissions("enchase:single:view")
	@RequestMapping(value = "cartonSelect")
	public String cartonSelect(CartonInfo cartonInfo, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		// 查询一览页面数据
		List<CartonInfo> cartonSelectList = enchaseService.findCartonInfoList(cartonInfo);
		cartonInfo.setCartonInfoList(cartonSelectList);

		// 将page值赋值给mvc model层返回jsp页面
		model.addAttribute("cartonInfo", cartonInfo);

		// 返回页面地址
		return "modules/trade/cartonSelect";
	}

	/**
	 * @Title: addExportDetail @Description: 添加出口成品明细 @param @param
	 * handBook @param @param session @param @return @return String @throws
	 */

	@RequiresPermissions("enchase:single:edit")
	@RequestMapping(value = "addCarton")
	public String addCarton(Enchase enchase, HttpServletRequest request, HttpServletResponse response, Model model) {
		try {

			// 查询一览页面数据
			CartonInfo pCartonInfo = new CartonInfo();
			pCartonInfo.setCommaCartonId(enchase.getCommaCartonId());
			List<CartonInfo> returnCartonInfo = enchaseService.findCartonInfoList(pCartonInfo);

			// 添加纸箱信息
			if (!CollectionsUtils.isEmpty(returnCartonInfo)) {
				if (CollectionsUtils.isEmpty(enchase.getCartonInfoList())) {
					enchase.setCartonInfoList(returnCartonInfo);
				} else {

					// 判断是否已经存在相同的纸箱
					for (CartonInfo newInfo : returnCartonInfo) {
						boolean isFind = false;
						for (CartonInfo oldInfo : enchase.getCartonInfoList()) {
							if (newInfo.getId().equals(oldInfo.getId())) {
								isFind = true;
								break;
							}
						}

						if (!isFind) {
							enchase.getCartonInfoList().add(newInfo);
						}
					}

				}
			}
			// 将page值赋值给mvc model层返回jsp页面
			model.addAttribute("enchase", enchase);

			// 返回地址
			return "modules/trade/enchaseCreate";
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 返回地址
			return "modules/trade/enchaseCreate";
		}

	}

	/**
	 * @Title: findIndentList @Description: 订单一览 @param @param
	 * handBook @param @param session @param @return @return String @throws
	 */
	@RequiresPermissions("enchase:single:edit")
	@RequestMapping(value = "indentList")
	public String findIndentList(Enchase enchase, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {

			// 获得选择的订单信息
			List<Enchase> resultIndentList = enchaseService.findIndentList(enchase.getIndentId());

			for (Enchase forEnchase : resultIndentList) {
				forEnchase.setUnPackNumber(forEnchase.getIndentNumber());
			}

			enchase.setIndentList(resultIndentList);

			// 尺码一览
			List<Enchase> resultSizeList = enchaseService.findSizeList(enchase.getIndentId());
			enchase.setAllSizeList(resultSizeList);

			// 清空箱单明细
			enchase.setPackageDetailsList(new ArrayList<Enchase>());

			// 将page值赋值给mvc model层返回jsp页面
			model.addAttribute("enchase", enchase);

			// 返回地址
			return "modules/trade/enchaseCreate";
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 返回地址
			return "modules/trade/enchaseCreate";
		}
	}

	/**
	 * @Title: addRowPackageDetails @Description: 添加箱单明细 @param @param
	 * enchase @param @param session @param @return @return String @throws
	 */

	@RequiresPermissions("enchase:single:edit")
	@RequestMapping(value = "addRowPackageDetails")
	public String addRowPackageDetails(Enchase enchase, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {

			Enchase pdInfo = new Enchase();
			// 设定客户合同号
			pdInfo.setCustomerContractNo(enchase.getIndentList().get(0).getCustomerContractNo());
			// 设定客户款号
			pdInfo.setStyleCustomerNo(enchase.getIndentList().get(0).getStyleCustomerNo());
			// 设定净重
			pdInfo.setCartonNetWeight(new BigDecimal("0"));
			// 设定尺码(只显示8个)
			pdInfo.setAllSizeList(enchase.getAllSizeList().subList(0, 8));
			// 箱号是否存在flg
			pdInfo.setHasCartonFromTo("0");
			// 纸箱体积
			pdInfo.setBoxVolume(enchase.getCartonInfoList().get(0).getCartonVolume());
			// 纸箱重量
			pdInfo.setBoxWeight(enchase.getCartonInfoList().get(0).getCartonWeight());

			if (CollectionsUtils.isEmpty(enchase.getPackageDetailsList())) {
				List<Enchase> pEnchaseList = new ArrayList<Enchase>();
				pEnchaseList.add(pdInfo);
				enchase.setPackageDetailsList(pEnchaseList);
			} else {
				enchase.getPackageDetailsList().add(pdInfo);
			}

			// 将page值赋值给mvc model层返回jsp页面
			model.addAttribute("enchase", enchase);

			// 返回地址
			return "modules/trade/enchaseCreate";
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 返回地址
			return "modules/trade/enchaseCreate";
		}
	}

	/**
	 * @Title: delExportDetail @Description: 删除进口料件明细 @param @param
	 * handBook @param @param model @param @param session @param @return @return
	 * String @throws
	 */

	@RequiresPermissions("enchase:single:edit")
	@RequestMapping(value = "delPackageDetail")
	public String delPackageDetail(Enchase enchase, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {

			enchase.getPackageDetailsList().remove(enchase.getTrIndex());

			// 将page值赋值给mvc model层返回jsp页面
			model.addAttribute("enchase", enchase);

			// 返回地址
			return "modules/trade/enchaseCreate";
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 返回地址
			return "modules/trade/enchaseCreate";
		}
	}

	/**
	 * 保存信息
	 * 
	 * @param enchase
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws ResourceException
	 */
	@RequiresPermissions("enchase:single:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(Enchase enchase, HttpServletRequest request, Model model, HttpServletResponse response,
			HttpSession session) throws ResourceException {

		// 判断id是否为null （判断新建或修改）
		if (enchase.getId() != null) {
			// 编辑数据
			// 判断数据是否删除
			Enchase enchaseNew = get(enchase.getId().toString());
			// 判断数据是否删除
			if (enchaseNew == null || BaseEntity.DEL_FLAG_DELETE.equals(enchaseNew.getDeleteFlag())) {
				// 返回提示信息
				return renderString(response,
						AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}

			// 排他处理
			if (enchase.getVersion() == get(enchase.getId().toString()).getVersion()) {

				// 版本号加1
				enchase.setVersion(enchase.getVersion() + 1);
			} else {

				// 返回提示信息
				return renderString(response,
						AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}
		}

		// 保存基准数据及子项数据
		enchaseService.saveEnchase(enchase);

		// 保存成功返回提示信息
		return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName("enchase_create_save_success")));
	}

	/**
	 * 进入查看页面
	 * 
	 * @param enchase
	 * @param model
	 * @return
	 */
	@RequiresPermissions("enchase:single:view")
	@RequestMapping(value = "show")
	public String show(Enchase enchase, Model model) {

		// 查找款式一览信息
		List<Enchase> resultIndentList = enchaseService.findIndentList(enchase.getIndentId());

		// 所有尺码一览
		List<Enchase> resultSizeList = enchaseService.findSizeList(enchase.getIndentId());
		enchase.setAllSizeList(resultSizeList);

		// 箱单明细一览取得
		List<Enchase> resultPackageDetailsList = enchaseService.findPackageDetailsList(enchase);

		if (!CollectionsUtils.isEmpty(resultPackageDetailsList)) {
			enchase.setPackageDetailsList(
					enchaseService.setPackageDetailsList(resultPackageDetailsList, resultSizeList));

			enchase.setIndentList(enchaseService.findShowIndentList(enchase.getPackageDetailsList(), resultIndentList));

			enchase.setCartonInfoList(enchaseService.findShowCartonInfoList(enchase.getPackageDetailsList()));
		}

		// 将查询结果赋值mvc model层返回jsp页面
		model.addAttribute("enchase", enchase);

		// 返回页面地址
		return "modules/trade/enchaseShow";
	}

	/**
	 * 删除信息
	 * 
	 * @param handBook
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 */
	@RequiresPermissions("enchase:single:edit")
	@RequestMapping(value = "delete")
	public String delete(Enchase enchase, HttpServletResponse response) {
		try {
			// 执行逻辑删除方法
			enchaseService.deleteEnchase(enchase);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 提示错误信息
			return renderString(response, AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		}

		// 提示删除成功信息
		return renderString(response, AjaxDone.ok(getText("enchase_show_delete_msg")));
	}
	
	@RequiresPermissions("enchase:single:view")
	@ResponseBody
	@RequestMapping(value = "exportFile")
	public String exportFile(Enchase enchase ,HttpServletResponse response){
		try {
            // 模版
            String basePath = SystemPath.getClassPath();
            String tempFilePath = "/" + basePath + "bigorder_enchase.xlsx";
            ExcelTemplate handle = this.enchaseService.exportBigOrderEnchase(enchase, tempFilePath);
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + enchase.getPackageNo() + ".xlsx");
            OutputStream os = response.getOutputStream();
            // 写到输出流并关闭资源
            handle.writeAndClose(tempFilePath, os);
            os.flush();
            os.close();
            handle.readClose(tempFilePath);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
	}
}
